package com.example.ddd.interfaces.rest;

import com.example.ddd.application.CustomerService;
import com.example.ddd.domain.model.Customer;
import com.example.ddd.interfaces.rest.dto.CreateCustomerRequest;
import com.example.ddd.interfaces.rest.dto.CustomerResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import jakarta.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/customers")
public class CustomerController {
    private final CustomerService customerService;

    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    @PostMapping
    public CustomerResponse create(@Valid @RequestBody CreateCustomerRequest request) {
        Customer saved = customerService.registerCustomer(request.getName(), request.getEmail());
        return new CustomerResponse(saved.getId(), saved.getName(), saved.getEmail());
    }

    @GetMapping("/{id}")
    public CustomerResponse get(@PathVariable Long id) {
        return customerService.getCustomer(id)
                .map(c -> new CustomerResponse(c.getId(), c.getName(), c.getEmail()))
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
    }

    @GetMapping
    public List<CustomerResponse> list() {
        return customerService.listCustomers().stream()
                .map(c -> new CustomerResponse(c.getId(), c.getName(), c.getEmail()))
                .collect(Collectors.toList());
    }
}